#!/bin/bash

# Satis构建脚本
set -e

SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
cd "$SCRIPT_DIR" || exit

CONFIG_FILE="satis.json"
OUTPUT_DIR="./public"
SSH_DIR="${HOME}/.ssh"
COMPOSER_HOME="${HOME}/.composer"
log() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# 检查SSH目录存在性
if [ ! -d "${SSH_DIR}" ]; then
  log "错误：SSH目录不存在 ${SSH_DIR}"
  exit 1
fi

log "正在获取远程更新..."
git fetch origin
log "正在更新代码..."
git reset --hard origin/main

# 执行构建
log "开始执行构建..."
docker run --rm --init \
  --volume $(pwd):/build \
  --volume "${SSH_DIR}:/root/.ssh" \
  --volume "${COMPOSER_HOME}:/composer" \
  composer/satis build "/build/${CONFIG_FILE}" "/build/${OUTPUT_DIR}"

# 执行清理
log "开始执行清理..."
docker run --rm --init \
  --volume $(pwd):/build \
  --volume "${SSH_DIR}:/root/.ssh" \
  --volume "${COMPOSER_HOME}:/composer" \
  composer/satis purge "/build/${CONFIG_FILE}" "/build/${OUTPUT_DIR}"

log "构建完成！输出目录: ${OUTPUT_DIR}"
